A nossa empresa e seus investidores decidiram montar um time de futebol na Europa com a mesma qualidade dos melhores times europeus da atualidade. Para isso, solicitaram uma análise da equipe de BI sobre quais jogadores poderiam adquirir, desde que tivessem um preço competitivo. Devemos contratar 11 jogadores titulares para as seguintes posições:
| Posição | Descrição | Jogadores |
|---|---|---|
| GK | Goleiro | 1 |
| Center-back | Zagueiro central | 2 |
| Outside-back | Zagueiro lateral | 2 |
| Center-mid | Meio de campo | 2 |
| Outside-mid | Lateral | 2 |
| Forward | Atacante | 2 |
As posições detalhadas podem ser encontradas na figura a seguir:
Como não é possível medir todos os jogadores do mundo a partir de agora, o novo time considerou aceitável usar a base de dados com 17994 jogadores (originários do jogo Fifa 18).
Informações dos jogadores:
ID, name, full_name, club, club_logo, special, league, flag, nationality, photo, Position.
Habilidades do jogador (numéricos):
crossing, finishing, heading_accuracy, short_passing, volleys, dribbling, curve, free_kick_accuracy, long_passing, ball_control, acceleration, sprint_speed, agility, reactions, balance, shot_power, jumping, stamina, strength, long_shots, aggression, interceptions, positioning, vision, penalties, composure, marking, standing_tackle, sliding_tackle, gk_diving, gk_handling, gk_kicking, gk_positioning, gk_reflexes.
Características físicas:
Numéricos: age, height_cm, weight_kg.
Categóricos: birth_date, body_type.
Booleano: real_face
Dados financeiros (numéricos):
eur_value, eur_wage, eur_release_clause
Para iniciarmos a análise é preciso instalar e carregar alguns pacotes. Esta seção é considerada um cabeçalho e evolui conforme a análise acontece.
Obs.: Caso sua estação não possua algum dos pacotes, é necessário instalar antes!
library(DBI) #Interface para base de dados
library(RPostgres) #Conexão com base de dados
library(readr) #Leitura de arquivo CSV
library(openxlsx) # Leitura de arquivo Excel
library(dplyr) #Manipulação de dados
library(plotly) #Gráficos Interativos
library(randomForest) #Aprendizado estatístico Advanced Analytics
library(magrittr)
A seguir, serão criadas algumas funções auxiliares que serão utilizadas em diversos trechos de análise.
#O professor criou a função abaixo para dar o display de um gráfico do plotly sempre com o mesmo tamanho
display.graph <- function(mygraph, width = 800, height = 500, margin = 0){
ret <- mygraph %>%
layout(autosize = F, width = width, height = height, margin = margin) %>%
config(showLink = F)
return ( ret )
}
A seguir temos exemplos de obtenção de dados de arquivo csv, arquivo Excel e banco de dados. Utilize seu conhecimento para obter as informações requeridas indicadas na seção 1:
# Exemplo Excel
exemplo.cameras <- read.xlsx("https://storage.googleapis.com/ds-publico/cameras.baltimore.xlsx")
# Exemplo CSV
exemplo.copas <- read_csv(url("https://storage.googleapis.com/ds-publico/Copas.csv"))
## Rows: 20 Columns: 10
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (6): Country, Winner, Runners-Up, Third, Fourth, Attendance
## dbl (4): Year, GoalsScored, QualifiedTeams, MatchesPlayed
##
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# Exemplo DB
con <- dbConnect(Postgres(), host="35.225.23.89", port=55432,
db="fiapbi", user="biuser", password="biuser")
exemplo.starwars <- dbGetQuery(con, "SELECT * FROM public.starwars")
exemplo.school_persons <- dbGetQuery(con, "SELECT * FROM reports.school_persons")
dbDisconnect(con)
rm(con)
Insira na célula a seguir os passos para obtenção dos dados mencionados. Lembre-se de armazenar em variáveis com nomes apropriados.
## COLOQUE SUA RESPOSTA AQUI
players = read.xlsx("https://storage.googleapis.com/ds-publico/Fifa/jogadores.xlsx")
con = dbConnect(Postgres(), host="35.225.23.89", port=55432, db="fiapbi", user="biuser", password="biuser")
habilities = dbGetQuery(con, "SELECT * FROM futebol.habilities")
physical = dbGetQuery(con, "SELECT * FROM futebol.body")
dbDisconnect(con)
rm(con)
finances = read_csv("https://storage.googleapis.com/ds-publico/Fifa/financial.csv")
## Rows: 17994 Columns: 4
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## dbl (4): ID, eur_value, eur_wage, eur_release_clause
##
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
Para facilitar todas as análises a seguir, crie uma tabela chamada fifa, com o “join” de todas as tabelas (use inner_join)
## COLOQUE SUA RESPOSTA AQUI
fifa = players %>%
inner_join(habilities,by="ID") %>%
inner_join(physical, by="ID") %>%
inner_join(finances, by="ID")
if(!'fifa' %in% ls()){
print("Querido aluno, a tabela 'fifa' precisa existir!")
} else {
print("Parece que está certo, vamos seguir!")
}
## [1] "Parece que está certo, vamos seguir!"
Todo processamento deve se iniciar de uma análise exploratória, ou seja, conhecer os dados que temos disponíveis.
Para isso, vamos usar alguns conceitos de estatística descritiva.
Os códigos a seguir exibem informações sobre uma tabela chamada mtcars, entre estes dados:
- Quantidade de linhas e colunas;
- Resumos estatísticos das colunas;
- Primeiros registros da tabela.
dim(mtcars)
## [1] 32 11
summary(mtcars)
## mpg cyl disp hp
## Min. :10.40 Min. :4.000 Min. : 71.1 Min. : 52.0
## 1st Qu.:15.43 1st Qu.:4.000 1st Qu.:120.8 1st Qu.: 96.5
## Median :19.20 Median :6.000 Median :196.3 Median :123.0
## Mean :20.09 Mean :6.188 Mean :230.7 Mean :146.7
## 3rd Qu.:22.80 3rd Qu.:8.000 3rd Qu.:326.0 3rd Qu.:180.0
## Max. :33.90 Max. :8.000 Max. :472.0 Max. :335.0
## drat wt qsec vs
## Min. :2.760 Min. :1.513 Min. :14.50 Min. :0.0000
## 1st Qu.:3.080 1st Qu.:2.581 1st Qu.:16.89 1st Qu.:0.0000
## Median :3.695 Median :3.325 Median :17.71 Median :0.0000
## Mean :3.597 Mean :3.217 Mean :17.85 Mean :0.4375
## 3rd Qu.:3.920 3rd Qu.:3.610 3rd Qu.:18.90 3rd Qu.:1.0000
## Max. :4.930 Max. :5.424 Max. :22.90 Max. :1.0000
## am gear carb
## Min. :0.0000 Min. :3.000 Min. :1.000
## 1st Qu.:0.0000 1st Qu.:3.000 1st Qu.:2.000
## Median :0.0000 Median :4.000 Median :2.000
## Mean :0.4062 Mean :3.688 Mean :2.812
## 3rd Qu.:1.0000 3rd Qu.:4.000 3rd Qu.:4.000
## Max. :1.0000 Max. :5.000 Max. :8.000
head(mtcars)
Use o exemplo acima e informe :
dim(fifa)
## [1] 17994 49
summary(fifa)
## ID name full_name club
## Min. : 16 Length:17994 Length:17994 Length:17994
## 1st Qu.:192621 Class :character Class :character Class :character
## Median :214186 Mode :character Mode :character Mode :character
## Mean :207792
## 3rd Qu.:231616
## Max. :241489
##
## special league nationality Position
## Min. : 728 Length:17994 Length:17994 Length:17994
## 1st Qu.:1450 Class :character Class :character Class :character
## Median :1634 Mode :character Mode :character Mode :character
## Mean :1594
## 3rd Qu.:1785
## Max. :2291
##
## crossing finishing heading_accuracy short_passing
## Min. : 5.00 Min. : 2.00 Min. : 4.00 Min. :10.00
## 1st Qu.:38.00 1st Qu.:29.00 1st Qu.:45.00 1st Qu.:53.00
## Median :54.00 Median :48.00 Median :56.00 Median :62.00
## Mean :49.81 Mean :45.33 Mean :52.38 Mean :58.34
## 3rd Qu.:64.00 3rd Qu.:61.75 3rd Qu.:64.00 3rd Qu.:68.00
## Max. :90.00 Max. :95.00 Max. :94.00 Max. :92.00
##
## volleys dribbling curve free_kick_accuracy
## Min. : 4.00 Min. : 2.00 Min. : 6.00 Min. : 4.00
## 1st Qu.:30.00 1st Qu.:48.00 1st Qu.:34.00 1st Qu.:31.00
## Median :44.00 Median :61.00 Median :49.00 Median :42.00
## Mean :43.23 Mean :55.11 Mean :47.33 Mean :43.17
## 3rd Qu.:57.00 3rd Qu.:68.00 3rd Qu.:62.00 3rd Qu.:57.00
## Max. :91.00 Max. :97.00 Max. :92.00 Max. :93.00
##
## long_passing ball_control acceleration sprint_speed
## Min. : 7.00 Min. : 8.00 Min. :11.00 Min. :11.00
## 1st Qu.:42.00 1st Qu.:53.00 1st Qu.:57.00 1st Qu.:57.00
## Median :56.00 Median :63.00 Median :67.00 Median :67.00
## Mean :52.48 Mean :58.14 Mean :64.65 Mean :64.89
## 3rd Qu.:64.00 3rd Qu.:69.00 3rd Qu.:75.00 3rd Qu.:75.00
## Max. :93.00 Max. :95.00 Max. :96.00 Max. :96.00
##
## agility reactions balance shot_power jumping
## Min. :14.00 Min. :28.0 Min. :11.00 Min. : 3.00 Min. :13.00
## 1st Qu.:55.00 1st Qu.:56.0 1st Qu.:56.00 1st Qu.:46.00 1st Qu.:58.00
## Median :65.00 Median :62.0 Median :66.00 Median :59.00 Median :66.00
## Mean :63.35 Mean :61.9 Mean :63.81 Mean :55.67 Mean :64.89
## 3rd Qu.:74.00 3rd Qu.:68.0 3rd Qu.:74.00 3rd Qu.:69.00 3rd Qu.:73.00
## Max. :96.00 Max. :96.0 Max. :96.00 Max. :94.00 Max. :95.00
##
## stamina strength long_shots aggression interceptions
## Min. :12.0 Min. :12.00 Min. : 3.00 Min. :11.00 Min. : 4.00
## 1st Qu.:56.0 1st Qu.:58.00 1st Qu.:33.00 1st Qu.:43.00 1st Qu.:26.00
## Median :66.0 Median :66.00 Median :51.00 Median :59.00 Median :52.00
## Mean :63.3 Mean :65.29 Mean :47.24 Mean :55.83 Mean :46.58
## 3rd Qu.:74.0 3rd Qu.:74.00 3rd Qu.:63.00 3rd Qu.:69.00 3rd Qu.:64.00
## Max. :95.0 Max. :98.00 Max. :92.00 Max. :96.00 Max. :92.00
##
## positioning vision penalties composure
## Min. : 2.00 Min. :10.00 Min. : 5.00 Min. : 5.00
## 1st Qu.:38.00 1st Qu.:43.00 1st Qu.:39.00 1st Qu.:51.00
## Median :55.00 Median :55.00 Median :50.00 Median :60.00
## Mean :49.68 Mean :53.03 Mean :48.99 Mean :57.89
## 3rd Qu.:64.00 3rd Qu.:64.00 3rd Qu.:61.00 3rd Qu.:67.00
## Max. :95.00 Max. :94.00 Max. :92.00 Max. :96.00
##
## marking standing_tackle sliding_tackle gk_diving gk_handling
## Min. : 4.00 Min. : 4.00 Min. : 4.00 Min. : 1.0 Min. : 1.00
## 1st Qu.:22.00 1st Qu.:26.00 1st Qu.:24.00 1st Qu.: 8.0 1st Qu.: 8.00
## Median :48.00 Median :54.00 Median :52.00 Median :11.0 Median :11.00
## Mean :44.12 Mean :47.48 Mean :45.59 Mean :16.7 Mean :16.48
## 3rd Qu.:63.00 3rd Qu.:66.00 3rd Qu.:64.00 3rd Qu.:14.0 3rd Qu.:14.00
## Max. :92.00 Max. :92.00 Max. :91.00 Max. :91.0 Max. :91.00
##
## gk_kicking gk_positioning gk_reflexes age
## Min. : 1.00 Min. : 1.00 Min. : 1.00 Min. :16.00
## 1st Qu.: 8.00 1st Qu.: 8.00 1st Qu.: 8.00 1st Qu.:21.00
## Median :11.00 Median :11.00 Median :11.00 Median :25.00
## Mean :16.36 Mean :16.47 Mean :16.83 Mean :25.12
## 3rd Qu.:14.00 3rd Qu.:14.00 3rd Qu.:14.00 3rd Qu.:28.00
## Max. :95.00 Max. :91.00 Max. :90.00 Max. :47.00
##
## height_cm weight_kg birth_date eur_value
## Min. :155.0 Min. : 49.0 Length:17994 Min. : 0
## 1st Qu.:177.0 1st Qu.: 70.0 Class :character 1st Qu.: 300000
## Median :181.0 Median : 75.0 Mode :character Median : 700000
## Mean :181.3 Mean : 75.4 Mean : 2370511
## 3rd Qu.:186.0 3rd Qu.: 80.0 3rd Qu.: 2000000
## Max. :205.0 Max. :110.0 Max. :123000000
##
## eur_wage eur_release_clause
## Min. : 0 Min. : 13000
## 1st Qu.: 2000 1st Qu.: 528000
## Median : 4000 Median : 1200000
## Mean : 11504 Mean : 4449111
## 3rd Qu.: 12000 3rd Qu.: 3600000
## Max. :565000 Max. :236800000
## NA's :1494
Qual a quantidade de jogadores no arquivo de jogadores: 17994
Qual o salário médio dos jogadores, em Euro: 11504
O exemplo abaixo exibe quantas espécies diferentes temos na tabela exemplo.starwars
length( unique(exemplo.starwars$species) )
## [1] 38
Baseado nisso, quantos Clubes e quantas ligas temos disponíveis:
length(unique(fifa$club))
## [1] 648
length(unique(fifa$league))
## [1] 42
Quantos jogadores temos em cada liga? Use o exemplo abaixo para responder.
exemplo.starwars %>%
group_by(species) %>%
summarise(Personagens = n()) %>%
arrange(desc(Personagens))
Reposta:
fifa %>%
group_by(league) %>%
summarise(players = n()) %>%
arrange(desc(players))
Nossa base de dados possui 647 times divididos em 41 ligas. As seguintes ligas serão selecionadas como as melhores ligas para análise dos jogadores:
- English Championship
- French Ligue 1
- German Bundesliga
- Spanish Primera División
- Italian Serie A (ok, sei que há controvérsias)
Para faciliar nosso trabalho futuro, armazenamos as ligas de referência selecionadas no vetor best_leagues:
best_leagues = c("English Championship", "French Ligue 1", "German Bundesliga", "Spanish Primera División", "Italian Serie A")
best_species = c("Droid", "Mirialan")
Agora exiba um gráfico nos informando quantos jogadores estão na liga de referência. Veja o exemplo abaixo que exibe quantos personages estão nas espécies de referência:
exemplo.starwars %>%
group_by(species) %>%
summarise(Personagens = n()) %>%
arrange(desc(Personagens)) %>%
mutate( Referencia = species %in% best_species) -> exemplo.agregacao
print(exemplo.agregacao)
## # A tibble: 38 × 3
## species Personagens Referencia
## <chr> <int> <lgl>
## 1 Human 35 FALSE
## 2 Droid 6 TRUE
## 3 NA 4 FALSE
## 4 Gungan 3 FALSE
## 5 Kaminoan 2 FALSE
## 6 Mirialan 2 TRUE
## 7 Twi'lek 2 FALSE
## 8 Wookiee 2 FALSE
## 9 Zabrak 2 FALSE
## 10 Aleena 1 FALSE
## # … with 28 more rows
## COLOQUE SUA RESPOSTA AQUI
n_players_by_league = fifa %>%
group_by(league) %>%
summarise(players = n()) %>%
arrange(desc(players)) %>%
mutate(reference = league %in% best_leagues) %T>%
print()
## # A tibble: 42 × 3
## league players reference
## <chr> <int> <lgl>
## 1 Argentinian Superliga 780 FALSE
## 2 English Championship 717 TRUE
## 3 English League One 668 FALSE
## 4 English Premier League 654 FALSE
## 5 Spanish Segunda División 637 FALSE
## 6 English League Two 633 FALSE
## 7 Italian Serie B 625 FALSE
## 8 USA Major League Soccer 625 FALSE
## 9 Spanish Primera División 602 TRUE
## 10 French Ligue 1 598 TRUE
## # … with 32 more rows
Exiba o gráfico de barras de todas as ligas, destacando as que são ligas de referência. Use o exemplo abaixo:
grafico <- exemplo.agregacao %>%
filter(Referencia == F) %>%
plot_ly(x = ~species, y = ~Personagens, color = ~Referencia, type = 'bar', name="Outras")
grafico <- grafico %>% add_bars(x = ~species, y = ~Personagens, color = ~Referencia, data = exemplo.agregacao[exemplo.agregacao$Referencia==T,], name="Best")
display.graph(grafico)
Minhas ligas, se tudo der certo, um gráfico como este deve ser exibido: